package cn.tx.util;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class JSONWriter {
	
	/**
	 * 向前台页面写回json数组格式的字符串
	 * @param list
	 * @param resp
	 */
	public static void writeJSONArray(Collection<?> list, HttpServletResponse resp){
		JSONArray ja = JSONArray.fromObject(list);
		String result = ja.toString();
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		try {
			resp.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 向前台页面写回json数组格式的字符串，但是可以排除list中对象的某些属性。
	 * @param list
	 * @param resp
	 * @param exclude
	 */
	public static void writeJSONArray(Collection<?> list, HttpServletResponse resp, String [] exclude){
		//创建json配置对象
		JsonConfig jc = new JsonConfig();
		//设置排除的属性，延迟加载的属性我们需要排除
		jc.setExcludes(exclude);
		
		try {
			System.out.println(list);
			JSONArray ja = JSONArray.fromObject(list, jc);
			String result = ja.toString();
			System.out.println(result);
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("text/html;charset=UTF-8");
			resp.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 向前台页面写回单个对象的字符串，带有排除属性的
	 * @param obj
	 * @param resp
	 * @param exclude
	 */
	public static void writeJSONObj(Object obj, HttpServletResponse resp, String [] exclude){
		//创建json配置对象
		JsonConfig jc = new JsonConfig();
		//设置排除的属性，延迟加载的属性我们需要排除
		jc.setExcludes(exclude);
		JSONObject ja = JSONObject.fromObject(obj, jc);
		String result = ja.toString();
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		try {
			resp.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 向前台页面写回单个对象的字符串
	 * @param obj
	 * @param resp
	 */
	public static void writeJSONObj(Object obj, HttpServletResponse resp){
		
		JSONObject ja = JSONObject.fromObject(obj);
		String result = ja.toString();
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		try {
			resp.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void writeString(Object obj, HttpServletResponse resp){
		String result = obj.toString();
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		try {
			resp.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
